home *** CD-ROM | disk | FTP | other *** search
- Path: trib.apple.com!usenet
- From: Amir <Amir@bayarea.net>
- Newsgroups: comp.lang.c++
- Subject: Re: [HELP!!!] Segmentation Fault!
- Date: Mon, 08 Apr 1996 11:04:30 -0700
- Organization: Apple Computer, Inc., Cupertino, California
- Message-ID: <3169552E.B49@bayarea.net>
- References: <4k4gja$mm@nuscc.nus.sg>
- NNTP-Posting-Host: a17-128-200-53.apple.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01 (Macintosh; I; PPC)
-
- Hi
-
- I just stopped on the first major prob I found.
-
- Virus wrote:
- > ...
- >
- > char* SpaceStudentFile::readNextField()
- > {
- > char str[40];
- > int i = 0;
- >
- > // take away starting whitespaces
- > while (str[0] = fgetc(fd)) {
- > if (*str == ' ') continue;
- > if (*str == '\t') continue;
- > if (*str == '\n') continue;
- > if (*str == EOF) return NULL;
- > break;
- > }
- >
- > // read from " to next "
- > if (str[0] == '"') {
- > for (i=0; ((str[i] = fgetc(fd)) != '"'); i++)
- > ;
- > str[i]=0;
- > return str;
- > }
- >
- > // else read until next whitespace
- > for (i=1; ((str[i] = fgetc(fd)) != ' ')
- > && (str[i] != '\n') && (str[i] != '\t'); i++)
- > ;
- > str[i] = 0;
- > return str;
- >
- > }
- > ....
-
- str is a local variable, that means it is created when you
- call this method, and removed when the function returns to its
- caller, so when you do "return str" you actually return a pointer
- to a non existing string.
- There are several valid solutions, one of them is to allocate
- memory for it like:
-
- char* SpaceStudentFile::readNextField()
- {
- char str[40];
- char * newStr;
-
- ....
-
- str[i] = 0;
- newStr = strdup(str); // If your system doesn't have strdup you can use
- // newStr = malloc(strlen(str) + 1);
- // strcpy(newStr, str);
- return newStr;
- }
-
- This is a simple solution that will work, but this is not a very
- good one (you need to remember to free the memory when you
- don't need it anymore, and this is the C way, not C++). If you have
- some time to spend on this, than try to use in your classes the String
- class instead of "char *"
-
- Amir
-
-
- --
-
- \\||||//
- \ o o /
- ______________.ooO__( () )__Ooo._______________________________
-
- Amir Deutel http://www.bayarea.net/~amir/
-
- .oo0O O0oo. Work: Amir.D@AppleLink.Apple.com
- ( ) ( ) Home: Amir@bayarea.net
- __________________\ (_____) /____________________________________
- \_) (_/
-